#-*- coding: utf-8 -*-
'''
Created on 20/05/2012

@author: guilherme
'''
from ply import lex
from ply import yacc
from core.projection import Projection
from core.rename import Rename


# Tokens reconhecidos pela linguagem
tokens = (
          'LPAREN',
          'RPAREN',
          'OPERACAO',
          'CAMPO',
          'VIRGULA',
          'UNDERLINE',
          )

# Expressões regulares para os tokens
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_OPERACAO = r'(PI)|(RHO)|(GAMA)'
t_CAMPO = r'[a-zA-Z0-9]+'
t_VIRGULA = r','
t_UNDERLINE = r'_'

t_ignore  = ' \t'

def t_error(t):
    print "Illegal character '%s'" % t.value[0]
    t.lexer.skip(1)

# Build the lexer
lexer = lex.lex()
def p_comando_projection_multiple(p):
    """
    comando : OPERACAO UNDERLINE LPAREN campos RPAREN LPAREN comando RPAREN
    """
    if p[1] == 'PI':
        print Projection(p[4], p[7]).getSQL()
        return Projection(p[4], p[7]).getSQL()

def p_comando_projection(p):
    """
    comando : OPERACAO UNDERLINE LPAREN campos RPAREN LPAREN CAMPO RPAREN
    """
    if p[1] == 'PI':
        print Projection(p[4], p[7]).getSQL()
        return Projection(p[4], p[7]).getSQL()

def p_comando_selection(p):
    """
    comando : OPERACAO LPAREN campo VIRGULA campo RPAREN
    """
    if p[1] == 'RHO' :
        print Rename(p[3], p[5]).getSQL()
        return Rename(p[3], p[5]).getSQL()
    
def p_empty(t):
    'empty : '
    pass

def p_campos(p):
    """
    campos  : campos VIRGULA CAMPO
    """
    p[0] = p[1] + [p[3]]

def p_campos_sing(p):
    """
    campos  : CAMPO
    """
    p[0] = [p[1]]
    
def p_campo(p):
    """
    campo : CAMPO
    """
    p[0] = p[1]
    
def p_error(p):
    raise TypeError("unknown text at %r" % (p.value,))
    
yacc.yacc()
s = 'PI_(RHO(aaa,bbb))(tabela)'
yacc.parse(s)
s = 'RHO(DSAJDJ, DSADSAH)'
yacc.parse(s)



